<template>
  <div class="home">
    <div class="head">
      <div class="back" @click="methods.back">&lt; 返回</div>
      <p class="title">商品详情</p>
    </div>
    <div class="shop-box">
      <div class="img-box">
        <!-- <img :src="shopMes?.large_img" alt="" /> -->
        <img :src="shopMes?.image_url" alt="" />
      </div>
      <div class="shop-message">
        <div class="shop-head">
          <div class="shop-name">
            <div class="name">{{ shopMes?.name }}</div>
            <div class="enname">{{ shopMes?.enname || shopMes?.name }}</div>
          </div>
          <div style="color: rgb(12, 52, 186)">￥{{ shopMes?.price }}</div>
        </div>
        <div class="shop-sel-box">
          <div v-for="(v, i) in shopLabels" :key="i" class="shop-sel">
            <div class="shop-sel-title">{{ v.title }}</div>
            <div
              v-for="(value, index) in v.rule"
              :key="index"
              class="shop-sel-item"
              :class="{ 'shop-sel-active': v.activeIndex === index }"
              @click="methods.activeChange(i, index)"
            >
              {{ value }}
            </div>
          </div>
        </div>
        <div class="shop-num">
          <div>选择数量</div>
          <div class="shop-sel-num">
            <div
              class="onReduce"
              :class="shopNum < 2 ? '' : 'allow'"
              @click="methods.onReduce"
            >
              -
            </div>
            {{ shopNum }}
            <div
              class="add"
              :class="shopNum < 99 ? 'allow' : ''"
              @click="methods.onAdd"
            >
              +
            </div>
          </div>
        </div>
        <div class="shop-content">
          <p>商品描述</p>
          <p>{{ shopMes?.description }}</p>
        </div>
      </div>
    </div>
    <div class="bottom-box">
      <van-action-bar>
        <van-action-bar-icon
          icon="bag"
          text="购物袋"
          :badge="shopbagNum"
          :color="shopbagNum > 0 ? 'rgb(12,52,186)' : '#000'"
          @click="methods.goShopbag"
        />
        <van-action-bar-icon
          icon="like"
          :text="isCollect ? '收藏' : '未收藏'"
          :color="isCollect ? 'rgb(12,52,186)' : '#000'"
          @click="methods.collect"
        />
        <van-action-bar-button
          color="rgb(106,145,236)"
          type="warning"
          text="加入购物车"
          @click="methods.addShopCar"
        />
        <van-action-bar-button
          color="rgb(12,52,186)"
          type="danger"
          text="立即购买"
          @click="methods.goIndent"
        />
      </van-action-bar>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { CoffeeDetailModel, GET, postFormData } from '@/api'
import { showToast } from 'vant'
import { onMounted, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { PageShopMesShopLabelsModel } from './model'
import { getToken } from '@/utils/token'
const router = useRouter()
const route = useRoute()

/** 商品详情 */
const shopMes = ref<Nullable<CoffeeDetailModel>>(null)
/** 商品标签 */
const shopLabels = ref<PageShopMesShopLabelsModel[]>([])
const shopNum = ref(1)
let pid = ''
const isCollect = ref(false)
/** 购物车数量 */
const shopbagNum = ref<number>(0)

// 是否登录
const isLogin = !!getToken()

const methods = {
  getPid(pid: string) {
    // if (!pid) {
    //   showToast('商品不存在')
    //   router.go(-1)
    //   return
    // }
    GET({
      url: `/detail/${pid}`
    })
      .then((res) => {
        console.log(res)
        shopMes.value = res.data || {}
        shopMes.value!.image_url =
          import.meta.env.VITE_APP_PROXY_URL + shopMes.value?.image_url

        // const arr = ['cream', 'milk', 'sugar', 'tem']
        // arr.forEach((item) => {
        //   if (shopMes.value?.[item]) {
        //     const rule = shopMes.value?.[item].split('/')
        //     const title = shopMes.value?.[`${item}_desc`]
        //     shopLabels.value.push({
        //       title,
        //       activeIndex: 0,
        //       rule
        //     })
        //   }
        // })
      })
      .catch((err) => {
        console.error(err)
      })
  },

  back() {
    router.go(-1)
  },
  activeChange(a, b) {
    shopLabels.value[a].activeIndex = b
  },
  onReduce() {
    if (shopNum.value > 1) {
      shopNum.value--
    }
  },
  onAdd() {
    if (shopNum.value < 99) {
      shopNum.value++
    } else if (shopNum.value === 99) {
      showToast('一次最多只能购买99件商品')
    }
  },
  collect() {
    if (!isLogin) {
      showToast('请先登录')
    } else {
      if (isCollect.value) {
        postFormData({
          url: '/collect/unlike',
          params: {
            pid
          }
        })
          .then((res) => {
            if (res.data) {
              showToast('已取消收藏')
              isCollect.value = false
            }
          })
          .catch((err) => {
            console.error(err)
          })
      } else {
        postFormData({
          url: '/collect/like',
          params: {
            pid
          }
        })
          .then((res) => {
            if (res.data) {
              showToast('收藏成功')
              isCollect.value = true
            }
          })
          .catch((err) => {
            console.error(err)
          })
      }
    }
  },
  /** 查询是否已被收藏 */
  isCollect() {
    if (!isLogin) return
    GET({
      url: '/collect',
      params: {
        pid
      }
    })
      .then((res) => {
        isCollect.value = res.data || false
      })
      .catch((err) => {
        console.error(err)
      })
  },
  /** 加入购物车 */
  addShopCar() {
    if (!isLogin) {
      showToast('请先登录')
    } else {
      // let rule = ''
      // shopLabels.value.forEach((v) => {
      //   rule += v.rule[v.activeIndex] + '/'
      // })
      // rule = rule.slice(0, -1)
      postFormData({
        url: '/shop/add',
        params: {
          pid,
          count: shopNum.value
          // rule
        }
      })
        .then((res) => {
          if (res.data.code === 3000) {
            showToast('加入购物车成功')
            methods.getshopbagNum()
          }
        })
        .catch((err) => {
          console.error(err)
        })
    }
  },
  /** 获取购物车数量 */
  getshopbagNum() {
    if (!isLogin) return
    GET({
      url: '/shop/count'
    })
      .then((res) => {
        shopbagNum.value = res.data ?? 0
      })
      .catch((err) => {
        console.error(err)
      })
  },
  goShopbag() {
    if (!isLogin) {
      showToast('请先登录')
    } else {
      router.push({ name: 'Shopbag' })
    }
  },
  goIndent() {
    if (!isLogin) {
      showToast('请先登录')
    } else {
      const count = shopNum
      // let rule = ''
      // shopLabels.value.forEach((v) => {
      //   rule += v.rule[v.activeIndex] + '/'
      // })
      // rule = rule.slice(0, -1)
      postFormData({
        url: '/shop/add',
        params: {
          pid,
          count: count.value
          // rule: rule
        }
      })
        .then((res) => {
          if (res.data) {
            router.push({ name: 'Shopbag' })
          }
        })
        .catch((err) => {
          console.error(err)
        })
    }
  }
}

onMounted(() => {
  pid = (route.query.pid ?? '') as string
  methods.getPid(pid)
  methods.isCollect()
  methods.getshopbagNum()
})
</script>

<style lang="less" scoped>
.home {
  text-align: center;
  font-size: 16px;
  .head {
    width: 100%;
    height: 40px;
    position: fixed;
    top: 0;
    left: 0;
    background-color: rgba(255, 255, 255, 0.5);
    z-index: 9;
    .title {
      margin: 0;
      line-height: 40px;
      font-size: 20px;
    }
    .back {
      height: 100%;
      line-height: 40px;
      color: rgb(0, 119, 255);
      padding: 0 10px;
      position: absolute;
      top: 0;
      left: 0;
    }
  }
  .shop-box {
    width: 100%;
    padding-top: 40px;
    .shop-message {
      width: 90%;
      min-height: 60%;
      padding-bottom: 90px;
      box-sizing: border-box;
      background-color: #fff;
      box-shadow: 0 0px 1px 1px #ddd;
      border-top-left-radius: 16px;
      border-top-right-radius: 16px;

      position: absolute;
      left: 5%;
      top: 40%;
      p {
        margin: 10px 0;
      }
      .shop-head {
        padding: 20px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        border-bottom: 1px solid #ddd;
        .shop-name {
          text-align: left;
        }
        .name {
          font-weight: bold;
        }
        .enname {
          font-size: 12px;
        }
      }
      .shop-sel-box {
        padding: 20px 0;
        border-bottom: 1px solid #ddd;
        .shop-sel {
          display: flex;
          align-items: center;
          margin-top: 10px;
          padding: 0 20px;
          .shop-sel-title {
            width: 48px;
            text-align: left;
            margin-right: 20px;
          }
          .shop-sel-item {
            min-width: 48px;
            padding: 2px 10px;
            border-radius: 10px;
            background-color: #eee;
            margin-right: 10px;
          }
          .shop-sel-active {
            background-color: rgb(12, 52, 186);
            color: #fff;
          }
        }
      }
      .shop-num {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 20px;
        border-bottom: 1px solid #ddd;
        .shop-sel-num {
          width: 80px;
          display: flex;
          align-items: center;
          justify-content: space-between;
          .onReduce,
          .add {
            width: 20px;
            height: 20px;
            line-height: 20px;
            text-align: center;
            border-radius: 50%;
            border: 1px solid #bbb;
          }
          .allow {
            background-color: rgb(12, 52, 186);
            color: #fff;
          }
        }
      }
      .shop-content {
        text-align: left;
        p {
          margin: 0;
          margin-top: 10px;
          padding: 0 20px;
        }
      }
    }
    .img-box {
      width: 100%;
      margin: 0 auto;
      img {
        width: 100%;
      }
    }
  }

  .bottom-box {
    width: 100%;
    padding: 2px 0;
    display: flex;
    align-items: center;
    justify-content: space-around;
    height: 60px;
    background-color: #fff;
    position: fixed;
    bottom: 0;
    left: 0;
    border-top: 1px solid #eee;
  }
}
</style>
